<template>
  <div class="main-container">
    <el-form ref="createForm" :model="dataForm" :rules="rules">
      <!-- 表单内容器 -->
      <div class="data-show">
        <!-- 标题 -->
        <div class="data-actions">
          <h3>用户信息</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <!-- 配置项 - 算法名称 -->
            <div class="common-item item-3">
              <label class="condition-label">账号名</label>
              <el-form-item class="condition-input" prop="userName">
                <el-input type="text" placeholder="请输入用户名" v-model="dataForm.userName" />
              </el-form-item>
            </div>
            <div class="common-item item-3">
              <label class="condition-label">昵称</label>
              <el-form-item class="condition-input" prop="nickName">
                <el-input type="text" placeholder="请输入昵称" v-model="dataForm.nickName" />
              </el-form-item>
            </div>
            <div class="common-item item-3">
              <label class="condition-label">角色分配</label>
              <el-form-item class="condition-input" prop="roleKeys">
                <el-select @change="selectRole" collapse-tags collapse-tags-tooltip v-model="dataForm.selectRoles" multiple clearable placeholder="请选择用户角色">
                  <el-option v-for="(item, index) in roles" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <!-- 通用布局行 -->
          <!-- <div class="common-row row-between">
            
            <div class="common-item item-5">
              <label class="condition-label">模态分配</label>
              <el-form-item class="condition-input" prop="modalDos">
                <el-select @change="selectModal" collapse-tags collapse-tags-tooltip v-model="dataForm.selectModals" multiple clearable placeholder="请选择模态">
                  <el-option v-for="(item, index) in modals" :key="index" :label="item.modalName" :value="item.modalCode" />
                </el-select>
              </el-form-item>
            </div>
          </div> -->
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <div class="common-item item-5">
              <label class="condition-label">密码</label>
              <el-form-item class="condition-input" prop="password">
                <el-input type="password" v-model="dataForm.password" placeholder="请输入用户密码" show-password />
              </el-form-item>
            </div>
            <div class="common-item item-5">
              <label class="condition-label">确认密码</label>
              <el-form-item class="condition-input" prop="repeatPassword">
                <el-input type="password" v-model="dataForm.repeatPassword" placeholder="请再次输入用户密码" show-password />
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部的按钮 -->
      <div class="btn-groups">
        <button type="button" class="btn btn-normal" @click="back">返回</button>
        <button type="button" class="btn" @click="handleCreate">确定</button>
      </div>
    </el-form>
  </div>
</template>
<script setup>
import { global } from '@/utils/status.js';
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import useAppStore from '@/stores/app';
import * as userApi from '@/api/user';
import * as rule from '@/utils/rules.js';

// ============> data
const appStore = useAppStore();
const createForm = ref(null);
const router = useRouter();
const route = useRoute();
const roles = global.roleKeys;
const modals = ref([]);
// 表单对象
const dataForm = ref({
  userId: null,
  createFlag: false,
  userName: '',
  nickName: '',
  roleKeys: null,
  password: '',
  repeatPassword: '',
  modalDos: [],
  selectRoles: [],
  selectModals: []
});
const rules = {
  userName: rule.createRequiredRule('账号名不能为空'),
  // password: rule.createRequiredRule('密码不能为空'),
  password: rule.password,
  roleKeys: rule.createRequiredRule('用户角色不能为空'),
  repeatPassword: [
    { validator(rule,value, callback){
        if (!value){
          callback(new Error('请再次输入密码'));
        } else if (value != dataForm.value.password){
          callback(new Error('两次密码输入不一致，请核对'));
        } else {
          callback();
        }
      } 
    } 
  ]
};
// ============> hooks
onMounted(() => {
  console.log('onMounted')
  dataForm.value.userId = route.query && route.query.id ? route.query.id : null;
  init(); 
})


// ============> methods
async function init(){
  try {
    let modalsRes = await userApi.getModals();
    Array.isArray(modalsRes) && modalsRes.length > 0 && (modals.value = modalsRes);
    // dataForm.value.selectModals.push(modalsRes[0].modalCode);
    dataForm.value.modalDos.push(modalsRes[0])
  } catch(err){
    console.log(err);
  }
  if (dataForm.value.userId){
    try {
      let res = await userApi.getUserById({ userId: dataForm.value.userId });
      res && (dataForm.value = Object.assign(dataForm.value, res));
      if (typeof dataForm.value.roleKeys === 'string') dataForm.value.selectRoles = dataForm.value.roleKeys.split(',');
      if (Array.isArray(dataForm.value.modalDos) && dataForm.value.modalDos.length > 0) dataForm.value.selectModals = dataForm.value.modalDos.map(item => item.modalCode);
      console.log(dataForm.value)
    } catch(err){
      console.log(err);
    }
  }
}
const back = () => {
  router.replace({ name: 'userManage'});
}
function selectRole(e){
  if (Array.isArray(e) && e.length > 0) {
    dataForm.value.roleKeys = e.join(',');
  } else {
    dataForm.value.roleKeys = null;
  }
}
function selectModal(e){
  // console.log(e)
  // console.log(modals.value)
  if (Array.isArray(e) && e.length > 0){
    dataForm.value.modalDos =  e.reduce((res, modal) => {
      res.push(modals.value.find(item => item.modalCode === modal));
      return res;
    }, []);
  } else {
    dataForm.value.modalDos = [];
  }
}
function handleCreate(){
  console.log(dataForm.value)
  if (dataForm.value.createFlag){
    ElMessage.warning('当前正在处理中，请稍后');
    return;
  }
  // let apiFn = dataForm.value.userId ? userApi.setUser : userApi.addUser;
  let loadingTxt = dataForm.value.userId ? '修改用户信息中...' : '用户创建中...';
  let successTxt = dataForm.value.userId ? '修改用户信息成功！' : '创建用户成功！';
  createForm.value.validate(valid => {
    if (valid){
      dataForm.value.createFlag = true;
      appStore.openLoading(loadingTxt);
      userApi.addUser({...dataForm.value})
        .then(res => {
          // console.log(res);
          ElMessage.success(successTxt);
          router.replace({ name: 'userManage'});
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          dataForm.value.createFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息验证失败，请核对后提交');
    }
  })
}
</script>
<style lang='scss' scoped>
.item-7 {
  width: 70%;
  .condition-label {
    width: 20%;
  }
  .condition-input {
    width: 75%;
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.btn-red {
  background-color: var(--color-red);
}
</style>